package com.ancy.manager;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.ancy.common.PostData;

import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;

public class InternetManager {
	HttpClient httpclient;
	HttpGet httpget;
	HttpPost httppost;
	HttpResponse httpresponse;
	HttpEntity httpentity;
	String url;
	String response = "";
	byte[] data = null;
	public boolean IsServerConn = true;

	public InternetManager(String url) {
		this.url = url;
	}

	public String URLRequest() {

		httpclient = new DefaultHttpClient();
		try {
			httpget = new HttpGet(url);
			System.out.println("url" + url);
			httpresponse = httpclient.execute(httpget);
			httpentity = httpresponse.getEntity();
			response = EntityUtils.toString(httpentity);
			response = response.trim();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			IsServerConn = false;
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			IsServerConn = false;
		}
		return response;

	}

	public byte[] fileRequest() {
		httpclient = new DefaultHttpClient();
		httpget = new HttpGet(url);
		try {
			httpresponse = httpclient.execute(httpget);
			httpentity = httpresponse.getEntity();
			data = EntityUtils.toByteArray(httpentity);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.v("", "File downloaded URL: " + url);
		return data;
	}

	public static Boolean checkInternetConnection(Context context) {
		ConnectivityManager connec = (ConnectivityManager) context
				.getSystemService(context.CONNECTIVITY_SERVICE);
		if (connec.getNetworkInfo(0).isConnectedOrConnecting()
				|| connec.getNetworkInfo(1).isConnectedOrConnecting()) {
			return true;
		} else {
			return false;
		}
	}

	public String PostImageData(String fileName, String fileParameter,
			String urlString) {
		String response = "";
		HttpURLConnection conn = null;
		DataOutputStream dos = null;
		DataInputStream inStream = null;

		String exsistingFileName = fileName;
		// Is this the place are you doing something wrong.

		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";

		int bytesRead, bytesAvailable, bufferSize;

		byte[] buffer;

		int maxBufferSize = 1 * 1024 * 1024;

		String responseFromServer = "";

		// upload

		try {
			// ------------------ CLIENT REQUEST

			FileInputStream fileInputStream = new FileInputStream(new File(
					exsistingFileName));

			// open a URL connection to the Servlet

			URL url = new URL(urlString);

			// Open a HTTP connection to the URL

			conn = (HttpURLConnection) url.openConnection();

			// Allow Inputs
			conn.setDoInput(true);

			// Allow Outputs
			conn.setDoOutput(true);

			// Don't use a cached copy.
			conn.setUseCaches(false);

			// Use a post method.
			conn.setRequestMethod("POST");

			conn.setRequestProperty("Connection", "Keep-Alive");

			conn.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);

			dos = new DataOutputStream(conn.getOutputStream());

			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\""
					+ fileParameter + "\";filename=\"" + exsistingFileName
					+ "\"" + lineEnd);
			dos.writeBytes(lineEnd);

			// create a buffer of maximum size

			bytesAvailable = fileInputStream.available();
			bufferSize = Math.min(bytesAvailable, maxBufferSize);
			buffer = new byte[bufferSize];

			// read file and write it into form...

			bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			while (bytesRead > 0) {
				dos.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}

			// send multipart form data necesssary after file data...

			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

			// close streams
			Log.e("fileupload", "File is Saved");
			fileInputStream.close();
			dos.flush();
			dos.close();

		} catch (MalformedURLException ex) {
			Log.e("fileupload", "error: " + ex.getMessage(), ex);
			return "MalformedURLException";
		}

		catch (IOException ioe) {
			Log.e("Data upload", "error: " + ioe.getMessage(), ioe);
			return "IOException";
		}

		// ------------------ read the SERVER RESPONSE

		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			response = rd.readLine();
		} catch (IOException ioex) {
			Log.e("Data upload", "error: " + ioex.getMessage(), ioex);
			return "IOException";
		}
		return response;
	}

	public String postData(ArrayList<PostData> values) {
		// Create a new HttpClient and Post Header
		httpclient = new DefaultHttpClient();
		httppost = new HttpPost(url);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
				values.size());
		try {
			// Add your data
			for (int i = 0; i < values.size(); i++) {
				nameValuePairs.add(new BasicNameValuePair(values.get(i)
						.getParam(), values.get(i).getValue()));
			}
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			httpresponse = httpclient.execute(httppost);
			httpentity = httpresponse.getEntity();
			// Execute HTTP Post Request
			response = EntityUtils.toString(httpentity);
			response = response.trim();

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		return response;
	}

	public String getData(ArrayList<PostData> values) {
		// Create a new HttpClient and Post Header
		httpclient = new DefaultHttpClient();
		try {
			// Add your data
			for (int i = 0; i < values.size(); i++) {
				if (i == 0) {
					url += "?" + values.get(i).getParam() + "="
							+ values.get(i).getValue();
				} else {
					url += "&" + values.get(i).getParam() + "="
							+ values.get(i).getValue();

				}
			}
			System.out.println(url + ":url");
			httpget = new HttpGet(url);
			httpresponse = httpclient.execute(httpget);
			httpentity = httpresponse.getEntity();
			// Execute HTTP Post Request
			response = EntityUtils.toString(httpentity);
			response = response.trim();
			System.out.println(response + ":response");

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		return response;
	}
}
